class IP2Area:
	def __init__(self,indexfile,ipfile,tech=True):
		self.GetIndex(indexfile,ipfile)

	def GetIndex(self,indexfile,ipfile):
		self.__indexHash = {}
		self.__ipTable = []
		f = open(indexfile)
		for i in f:
			(ipSign,ip1,ip2) = i.split('\t')
			self.__indexHash[int(ipSign)] = (int(ip1),int(ip2.strip()))
		f.close()
		f = open(ipfile)
		for i in f:
			self.__ipTable.append(list(i.strip().split('\t')[:5]))
		f.close()

	def GetCityInfo_old(self,ipadd):
		f,s,t,fo = ipadd.split('.')
		ipInd = int(f)*1000+int(s)
		ipNumber = int(f)*1000**3+int(s)*1000**2+int(t)*1000+int(fo)
		if ipInd in self.__indexHash:
			startGrep,endGrep = self.__indexHash[ipInd]
			startGrep,endGrep = int(startGrep)-1,int(endGrep)-1
		else:
			return 'unknow oversea'
		while startGrep <= endGrep:
			provice,isp,city,ipSmall,ipLarge = lineInfo.getline('ipTable_final.txt',startGrep).split('\t')[:5]
			ipSmall,ipLarge = int(ipSmall),int(ipLarge)
			if ipNumber >= ipSmall and ipNumber <= ipLarge:
				return '|'.join([provice,isp,city])
			else:
				startGrep += 1

		else:
			return 'unknow oversea'

	def GetCityInfo(self,ipadd):
		try:
			f,s,t,fo = ipadd.split('.')
		except ValueError:
			print ipadd
			raise 'IP fmt Error'
		ipInd = int(f)*1000+int(s)
		ipNumber = int(f)*1000**3+int(s)*1000**2+int(t)*1000+int(fo)
		if ipInd in self.__indexHash:
			startGrep,endGrep = self.__indexHash[ipInd]
			#startGrep,endGrep = int(startGrep)-1,int(endGrep)-1
			startGrep,endGrep = int(startGrep),int(endGrep)
		else:
			return 'unknow oversea'

		while startGrep <= endGrep:
			try:
				[provice,isp,city,ipSmall,ipLarge] = self.__ipTable[startGrep-1]
			except IndexError:
				print ipadd,startGrep,endGrep

			ipSmall,ipLarge = int(ipSmall),int(ipLarge)
			if ipNumber >= ipSmall and ipNumber <= ipLarge:
				##old for return total info
				#return '|'.join([provice,isp,city])
				return '|'.join([provice,isp])
			else:
				startGrep += 1
		else:
			return 'unknow oversea'
